<template>
  <LoginHeader>联合登录</LoginHeader>
  <section class="container">
    <nav class="tab">
      <a
        href="javascript:;"
        @click="activeCom='CallbackBind'"
        :class="{ active: activeCom === 'CallbackBind' }"
      >
        <i class="iconfont icon-bind" />
        <span>已有小兔鲜账号，请绑定手机</span>
      </a>
      <a
        href="javascript:;"
         @click="activeCom='CallbackPatch'"
         :class="{ active: activeCom === 'CallbackPatch' }"
      >
        <i class="iconfont icon-edit" />
        <span>没有小兔鲜账号，请完善资料</span>
      </a>
    </nav>
    <!-- 动态组件 -->
    <!-- keep-alive是一个抽象组件：它自身不会渲染一个DOM元素，也不会出现在父组件链中；使用keep-alive包裹动态组件时，会缓存不活动的组件实例，而不是销毁它们 -->
    <keep-alive>
      <component :unionId="unionId" :is="activeCom"/>
    </keep-alive>
  </section>
  <LoginFooter />
</template>

<script>

import LoginHeader from './components/login-header'
import LoginFooter from './components/login-footer'
import CallbackBind from './components/callback-bind.vue'
import CallbackPatch from './components/callback-patch.vue'
import { ref } from 'vue-demi'
import QC from 'qc'
import { reqUserQQLogin } from '@/api/user'
import { useStore } from 'vuex'
import { message } from '@/components/Message'
import { useRouter } from 'vue-router'
export default {
  name: 'PageCallback',
  components: { LoginHeader, LoginFooter, CallbackBind, CallbackPatch },
  setup () {
    const store = useStore()
    const router = useRouter()

    const activeCom = ref('CallbackBind')
    const unionId = ref('')
    // QC.Login.check()  检查 QQ 是否登录，true 表示已登录
    if (QC.Login.check()) {
      // 获取当前登录用户的 openId：用户身份的唯一标识
      QC.Login.getMe(async (openId) => {
        console.log('获取到QQopenId：用户身份的唯一标识', openId)
        unionId.value = openId

        // 根据 unionId/openId 直接登录
        const { result } = await reqUserQQLogin(openId)
        // 1. 存储用户信息
        store.commit('user/setProfile', result)
        // 🔔 合并购物车
        await store.dispatch('cart/asyncMergeLocalCart')
        // 2. 跳转页面
        router.push('/')
        // 3. 提示
        message({ type: 'success', text: 'QQ授权登录成功' })
      })
    }

    return { activeCom, unionId }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding: 25px 0;
}
.tab {
  background: #fff;
  height: 80px;
  padding-top: 40px;
  font-size: 18px;
  text-align: center;
  a {
    color: #666;
    display: inline-block;
    width: 350px;
    line-height: 40px;
    border-bottom: 2px solid #e4e4e4;
    i {
      font-size: 22px;
      vertical-align: middle;
    }
    span {
      vertical-align: middle;
      margin-left: 4px;
    }
    &.active {
      color: @xtxColor;
      border-color: @xtxColor;
    }
  }
}
.tab-content {
  min-height: 600px;
  background: #fff;
}
</style>
